package com.approval.approvalapp.login;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approval.SldlActivity;
import com.approval.approvalapp.MainActivity;
import com.approval.approvalapp.MyAppliaction;
import com.approval.approvalapp.R;
import com.approval.approvalapp.bean.UserSessionBean;
import com.approval.approvalapp.util.DensityUtil;
import com.approval.approvalapp.util.ErrorBeanUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.ToastUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;

import androidx.annotation.NonNull;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {


    @Bind(R.id.phone_et)
    EditText phoneEt;
    @Bind(R.id.psw_et)
    EditText pswEt;
    @Bind(R.id.eye)
    ImageView eye;
    @Bind(R.id.login_btn)
    Button loginBtn;
    @Bind(R.id.root)
    LinearLayout root;
    public static LoginActivity instance;

    public boolean closeeye = true;
    @Bind(R.id.sldl_ll)
    LinearLayout sldlLl;
    @Bind(R.id.yzmdl_ll)
    LinearLayout yzmdlLl;
    @Bind(R.id.swdl_ll)
    LinearLayout swdlLl;
    private ProgressDialog progressDialog;
    @Bind(R.id.v1)
    View v1;
    @Bind(R.id.v2)
    View v2;

    @Override
    public int getLayoutId() {
        instance = this;
        return R.layout.activity_login;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void initView() {


        if (MyAppliaction.getInstance().isLogin()) {
            root.setVisibility(View.GONE);
        } else {
            root.setVisibility(View.VISIBLE);

            DensityUtil.changeViewSize(this, v1, 0.3f);
            DensityUtil.changeViewSize(this, v2, 0.17f);
        }

    }

    @Override
    public void initData() {
        //判断用户是否给这些权限授权
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED
                ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.
                    requestPermissions(this, new String[]{Manifest.permission.
                                    READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.ACCESS_FINE_LOCATION,
                                    Manifest.permission.ACCESS_COARSE_LOCATION,
                                    Manifest.permission.READ_PHONE_STATE},
                            1);
        } else {
            if (MyAppliaction.getInstance().isLogin()) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                        grantResults[1] == PackageManager.PERMISSION_GRANTED
                        &&
                        grantResults[2] == PackageManager.PERMISSION_GRANTED
                        && grantResults[3] == PackageManager.PERMISSION_GRANTED &&
                        grantResults[4] == PackageManager.PERMISSION_GRANTED &&
                        grantResults[5] == PackageManager.PERMISSION_GRANTED)) {
                    if (MyAppliaction.getInstance().isLogin()) {
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                } else {
                    Toast.makeText(this, "请给与权限", Toast.LENGTH_SHORT).show();

                    //引导用户到设置中去进行设置
                    Intent intent = new Intent();
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                    startActivity(intent);

                    finish();
                }
                break;
        }
    }


    @OnClick({R.id.eye, R.id.login_btn, R.id.sldl_ll, R.id.yzmdl_ll, R.id.swdl_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yzmdl_ll:
                Toast.makeText(instance, "正在开发", Toast.LENGTH_SHORT).show();
                break;
            case R.id.swdl_ll:
                Toast.makeText(instance, "正在开发", Toast.LENGTH_SHORT).show();
                break;
            case R.id.eye:
                closeeye = !closeeye;
                if (closeeye) {
                    eye.setImageResource(R.drawable.eye_off);
                    pswEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pswEt.setSelection(pswEt.getText().length());
                } else {
                    eye.setImageResource(R.drawable.eye_on);
                    pswEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pswEt.setSelection(pswEt.getText().length());
                }
                break;
            case R.id.sldl_ll:
                Intent intent = new Intent(this, SldlActivity.class);
                startActivity(intent);
                break;
            case R.id.login_btn:
                if (phoneEt.getText().length() == 0) {
                    ToastUtil.showToast(LoginActivity.this, "账号不能为空");
                    return;
                }
                if (pswEt.getText().length() == 0) {
                    ToastUtil.showToast(LoginActivity.this, "密码不能为空");
                    return;
                }
                progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("正在登陆");
                progressDialog.show();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("username", phoneEt.getText().toString());
                jsonObject.put("password", pswEt.getText().toString());
                NetRequsetUtil.getInstance().netRequestPostJson("v1/user/login", jsonObject.toString(), new NetDownResponse() {
                    @Override
                    public void success(String str) {
                        Log.d("LoginActivitaaay", str);
                        UserSessionBean userSessionBean = JSON.parseObject(str, UserSessionBean.class);
                        SpUtil.saveString(LoginActivity.this, SpUtil.USER_RUN_ID, userSessionBean.getUserid());
                        SpUtil.saveString(LoginActivity.this, SpUtil.USER_RUN_NICKNAME, userSessionBean.getName());
                        SpUtil.saveString(LoginActivity.this, SpUtil.UNIT_NAME, userSessionBean.getUnit_name());
                        SpUtil.saveString(LoginActivity.this, SpUtil.REGION_CODE, userSessionBean.getRegion_code());
                        SpUtil.saveString(LoginActivity.this, SpUtil.USER_AVATER, userSessionBean.getAvatar());
                        Log.d("LoginActivityss", userSessionBean.getRegion_code());
                        Log.d("LoginActivityss", userSessionBean.getOrg_code());
                        Log.d("LoginActivityss", userSessionBean.getUserid());
                        Log.d("LoginActivityss", userSessionBean.getF_userid());
                        SpUtil.saveString(LoginActivity.this, SpUtil.ORG_CODE, userSessionBean.getOrg_code());
                        SpUtil.saveString(LoginActivity.this, SpUtil.USER_NAME, userSessionBean.getUsername());
                        SpUtil.saveString(LoginActivity.this, SpUtil.F_userid, userSessionBean.getF_userid());
                        SpUtil.saveString(LoginActivity.this, SpUtil.F_orgcode, userSessionBean.getF_orgcode());
                        SpUtil.saveString(LoginActivity.this, SpUtil.F_orgname, userSessionBean.getF_orgname());
                        SpUtil.saveString(LoginActivity.this, SpUtil.Usertype, userSessionBean.getUsertype());
                        SpUtil.saveString(LoginActivity.this, SpUtil.SJLD, userSessionBean.getSJLD());
                        SpUtil.saveString(LoginActivity.this, SpUtil.SJLDN, userSessionBean.getSJLDN());
                        SpUtil.saveString(LoginActivity.this, SpUtil.GZFW1, userSessionBean.getGZFW1());
                        SpUtil.saveString(LoginActivity.this, SpUtil.GH, userSessionBean.getGh());
                        SpUtil.saveString(LoginActivity.this, SpUtil.orgename, userSessionBean.getOrgename());
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }

                    @Override
                    public void errowithresponse(String str) {
                        ErrorBeanUtil.getErrorMessage(str);
                    }

                    @Override
                    public void erro() {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }
                        ErrorBeanUtil.getErrorMessage(null);
                    }

                    @Override
                    public void finish() {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
